<template>
  <div class="top-navigation">
    <!-- 左侧区域 -->
    <div class="nav-left">
      <!-- 侧边栏切换按钮 -->
      <el-button
        class="sidebar-toggle"
        :icon="sidebarCollapsed ? Expand : Fold"
        circle
        @click="handleToggleSidebar"
      />
      
      <!-- 刷新按钮 -->
      <el-button
        class="refresh-btn"
        :icon="Refresh"
        circle
        @click="handleRefresh"
        :loading="refreshLoading"
      />
    </div>
    
    <!-- 右侧区域 -->
    <div class="nav-right">
      <!-- 全屏切换 -->
      <el-tooltip content="全屏" placement="bottom">
        <el-button
          class="nav-btn"
          :icon="isFullscreen ? OfficeBuilding : FullScreen"
          circle
          @click="toggleFullscreen"
        />
      </el-tooltip>
      
      <!-- 消息通知 -->
      <el-badge :value="notificationCount" :hidden="notificationCount === 0" class="notification-badge">
        <el-button
          class="nav-btn"
          :icon="Bell"
          circle
          @click="showNotifications"
        />
      </el-badge>
      
      <!-- 管理员信息下拉菜单 -->
      <el-dropdown class="user-dropdown" @command="handleUserCommand">
        <div class="user-info">
          <el-avatar
            :key="avatarUrl || 'default'"
            :size="32"
            :src="avatarUrl"
            :icon="UserFilled"
            class="user-avatar"
            fit="contain"
          />
          <div class="user-details">
            <span class="username">{{ userStore.displayName || 'Admin' }}</span>
            <span class="user-role">{{ userStore.userRole || '管理员' }}</span>
          </div>
          <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile" :icon="User">
              个人资料
            </el-dropdown-item>
            <el-dropdown-item command="settings" :icon="Setting">
              系统设置
            </el-dropdown-item>
            <el-dropdown-item divided command="logout" :icon="SwitchButton">
              退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    
    <!-- 通知抽屉 -->
    <el-drawer
      v-model="notificationDrawer"
      title="消息通知"
      direction="rtl"
      size="320px"
    >
      <div class="notification-content">
        <el-empty v-if="notifications.length === 0" description="暂无新消息" />
        <div v-else class="notification-list">
          <div
            v-for="notification in notifications"
            :key="notification.id"
            class="notification-item"
            :class="{ 'unread': !notification.read }"
          >
            <div class="notification-icon">
              <el-icon :color="getNotificationColor(notification.type)">
                <component :is="getNotificationIcon(notification.type)" />
              </el-icon>
            </div>
            <div class="notification-content">
              <h4>{{ notification.title }}</h4>
              <p>{{ notification.content }}</p>
              <span class="notification-time">{{ formatTime(notification.time) }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
/* eslint-disable no-undef */
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Expand, Fold, Refresh, FullScreen, OfficeBuilding, Bell,
  UserFilled, ArrowDown, User, Setting, SwitchButton,
  InfoFilled, WarningFilled, SuccessFilled
} from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'

// Props
defineProps({
  sidebarCollapsed: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['toggle-sidebar'])

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const refreshLoading = ref(false)
const isFullscreen = ref(false)
const notificationDrawer = ref(false)
const notificationCount = ref(3)

// 计算属性
const avatarUrl = computed(() => {
  return userStore.userInfo?.avatar_url || null
})

// 模拟通知数据
const notifications = ref([
  {
    id: 1,
    type: 'info',
    title: '系统更新',
    content: '系统已更新到最新版本 v2.1.0',
    time: new Date(Date.now() - 1000 * 60 * 30),
    read: false
  },
  {
    id: 2,
    type: 'warning',
    title: '数据异常',
    content: '检测到部分用户数据存在异常，请及时处理',
    time: new Date(Date.now() - 1000 * 60 * 60 * 2),
    read: false
  },
  {
    id: 3,
    type: 'success',
    title: '导入完成',
    content: '用户数据导入已完成，共导入 1,234 条记录',
    time: new Date(Date.now() - 1000 * 60 * 60 * 4),
    read: true
  }
])

// 切换侧边栏
const handleToggleSidebar = () => {
  emit('toggle-sidebar')
}

// 刷新页面
const handleRefresh = async () => {
  refreshLoading.value = true
  try {
    // 模拟刷新延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    window.location.reload()
  } finally {
    refreshLoading.value = false
  }
}

// 全屏切换
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
    isFullscreen.value = true
  } else {
    document.exitFullscreen()
    isFullscreen.value = false
  }
}

// 显示通知
const showNotifications = () => {
  notificationDrawer.value = true
  // 标记为已读
  notifications.value.forEach(notification => {
    notification.read = true
  })
  notificationCount.value = 0
}

// 用户下拉菜单命令处理
const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm(
          '确定要退出登录吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        userStore.logout()
        ElMessage.success('已退出登录')
        router.push('/login')
      } catch {
        // 用户取消
      }
      break
  }
}

// 获取通知图标
const getNotificationIcon = (type) => {
  const iconMap = {
    info: InfoFilled,
    warning: WarningFilled,
    success: SuccessFilled
  }
  return iconMap[type] || InfoFilled
}

// 获取通知颜色
const getNotificationColor = (type) => {
  const primaryColor = getComputedStyle(document.documentElement).getPropertyValue('--theme-primary').trim() || '#409EFF'
  const colorMap = {
    info: primaryColor,
    warning: '#E6A23C',
    success: '#67C23A'
  }
  return colorMap[type] || primaryColor
}

// 格式化时间
const formatTime = (time) => {
  const now = new Date()
  const diff = now - time
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else {
    return `${days}天前`
  }
}

// 监听全屏状态变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement
}

onMounted(() => {
  document.addEventListener('fullscreenchange', handleFullscreenChange)
})

onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
})
</script>

<style scoped>
.top-navigation {
  height: 64px;
  background-color: var(--bg-color, #ffffff);
  border-bottom: 1px solid var(--border-color, #e6e8eb);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: var(--shadow-light, 0 2px 8px rgba(0, 0, 0, 0.06));
  position: relative;
  z-index: 999;
}

/* 左侧区域 */
.nav-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.sidebar-toggle {
  border: none;
  background-color: var(--bg-color-secondary, #f8f9fa);
  color: var(--text-color-secondary, #666);
  transition: all 0.3s ease;
}

.sidebar-toggle:hover {
  background-color: var(--theme-primary-alpha-10, rgba(64, 158, 255, 0.1));
  color: var(--theme-primary, #409EFF);
}

.refresh-btn {
  border: none;
  background-color: var(--bg-color-secondary, #f8f9fa);
  color: var(--text-color-secondary, #666);
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  background-color: var(--theme-primary-alpha-10, rgba(64, 158, 255, 0.1));
  color: var(--theme-primary, #409EFF);
}

/* 右侧区域 */
.nav-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.nav-btn {
  border: none;
  background-color: var(--bg-color-secondary, #f8f9fa);
  color: var(--text-color-secondary, #666);
  transition: all 0.3s ease;
}

.nav-btn:hover {
  background-color: var(--theme-primary-alpha-10, rgba(64, 158, 255, 0.1));
  color: var(--theme-primary, #409EFF);
}

/* 通知徽章 */
.notification-badge {
  cursor: pointer;
}

.notification-badge :deep(.el-badge__content) {
  background-color: #f56c6c;
  border: 2px solid #ffffff;
}

/* 用户下拉菜单 */
.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.user-info:hover {
  background-color: var(--bg-color-secondary, #f8f9fa);
}

.user-avatar {
  flex-shrink: 0;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
  max-width: 120px;
}

.username {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-color-primary, #333);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.2;
}

.user-role {
  font-size: 12px;
  color: var(--text-color-secondary, #666);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.2;
}

.dropdown-icon {
  font-size: 12px;
  color: var(--text-color-tertiary, #999);
  transition: transform 0.3s ease;
}

.user-dropdown.is-active .dropdown-icon {
  transform: rotate(180deg);
}

/* 通知内容 */
.notification-content {
  padding: 0;
}

.notification-list {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s ease;
  cursor: pointer;
}

.notification-item:hover {
  background-color: #f8f9fa;
}

.notification-item.unread {
  background-color: #f0f4ff;
}

.notification-item.unread::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background-color: #2a5298;
}

.notification-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.notification-content h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.notification-content p {
  margin: 0 0 8px 0;
  font-size: 13px;
  color: #666;
  line-height: 1.4;
}

.notification-time {
  font-size: 12px;
  color: #999;
}

/* 下拉菜单样式 */
:deep(.el-dropdown-menu) {
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e6e8eb;
}

:deep(.el-dropdown-menu__item) {
  padding: 12px 16px;
  font-size: 14px;
  transition: all 0.3s ease;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: #f0f4ff;
  color: #2a5298;
}

:deep(.el-dropdown-menu__item.is-divided) {
  border-top: 1px solid #e6e8eb;
}

/* 抽屉样式 */
:deep(.el-drawer__header) {
  padding: 20px;
  border-bottom: 1px solid #e6e8eb;
  margin-bottom: 0;
}

:deep(.el-drawer__body) {
  padding: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .top-navigation {
    padding: 0 16px;
  }

  .nav-right {
    gap: 12px;
  }

  .user-details {
    display: none;
  }

  .user-info {
    padding: 8px;
  }
}

@media (max-width: 480px) {
  .nav-left {
    gap: 8px;
  }

  .nav-right {
    gap: 8px;
  }

  .notification-badge,
  .nav-btn:not(.user-dropdown .nav-btn) {
    display: none;
  }
}
</style>
